<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="surveyUserLoginIdstring">
        <el-input v-model="queryParams.surveyUserLoginIdstring" placeholder="请输入用户名" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="调查的id" prop="surveyId">
        <el-input v-model="queryParams.surveyId" placeholder="请输入调查的id" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="调查项目名称" prop="surveyUserTitle" label-width="100px">
        <el-input v-model="queryParams.surveyUserTitle" placeholder="请输入调查项目名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="调查的价格" prop="surveyUserPrice" label-width="100px">
        <el-input v-model="queryParams.surveyUserPrice" placeholder="请输入调查的价格" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!--      <el-form-item label="调查开始的时间" prop="surveyStartTime" label-width="112px">-->
      <!--        <el-date-picker clearable-->
      <!--          v-model="queryParams.surveyStartTime"-->
      <!--          type="date"-->
      <!--          value-format="YYYY-MM-DD"-->
      <!--          placeholder="请选择调查开始的时间">-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="调查结束的时间" prop="surveyStopTime" label-width="112px">-->
      <!--        <el-date-picker clearable-->
      <!--          v-model="queryParams.surveyStopTime"-->
      <!--          type="date"-->
      <!--          value-format="YYYY-MM-DD"-->
      <!--          placeholder="请选择调查结束的时间">-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <el-form-item label="调查状态" prop="surveyAuditStatus" label-width="112px">
        <el-select v-model="queryParams.surveyAuditStatus" placeholder="选择调查状态" style="width: 240px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <a-input v-hasPermi="['survey:surveyLog:batchExamine']" v-model:value="surveyUserIdStr" placeholder="请输入id" style="width: 240px;margin-left: 12px;" />
        <el-select v-hasPermi="['survey:surveyLog:batchExamine']" v-model="surveyAuditStatus" placeholder="修改状态" style="width: 240px;margin-left: 12px;">
          <el-option v-for="item in surveyAuditStatusOptions" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
       
        <el-button v-hasPermi="['survey:surveyLog:batchExamine']" style="margin-left: 12px;"
          @click="handleBatchExamine( surveyAuditStatus)">修改状态</el-button>
        <el-button icon="TopRight" @click="exportData" v-hasPermi="['survey:surveyLog:export']">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="surveyLogList" @selection-change="handleSelectionChange"
      :default-sort="defaultSort" @sort-change="handleSortChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="调查人ID" align="center" prop="surveyUserId" />
      <el-table-column label="用户名" align="center" prop="surveyUserName" />
      <el-table-column label="项目ID" align="center" prop="surveyId" />
      <el-table-column label="项目名称" align="center" prop="surveyUserTitle" />
      <el-table-column label="价格" align="center" prop="surveyUserPrice" />
      <el-table-column label="调查开始的时间" align="center" prop="surveyStartTime" width="180" sortable="custom"
        :sort-orders="['descending', 'ascending']">
        <template #default="scope">
          <span>{{ parseTime(scope.row.surveyStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调查结束的时间" align="center" prop="surveyStopTime" width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.surveyStopTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="耗时" align="center" width="180">
        <template #default="scope">
          <span>{{
            calculateDuration(
              scope.row.surveyStartTime,
              scope.row.surveyStopTime
            ).toFixed(1)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="规定时间" align="center" prop="surveyFixedtime" width="180" />
      <!-- <el-table-column label="审核状态" align="center" prop="examineStatus">
        <template #default="scope">
          <div style="display: flex; justify-content: center; align-items: center">
            <a-tag v-if="scope.row.examineStatus === 0" color="blue">待审核</a-tag>
            <a-tag v-if="scope.row.examineStatus === 1" color="success">审核成功</a-tag>
            <a-tag v-if="scope.row.examineStatus === 2" color="red">审核失败</a-tag>
          </div>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" align="center" prop="surveyAuditStatus">
        <template #default="scope">
          <div style="display: flex; justify-content: center; align-items: center">
            <el-button type="primary" loading v-if="scope.row.surveyAuditStatus === '进行中'">
              <template #loading>
                <div class="custom-loading">
                  <svg class="circular" viewBox="-10, -10, 50, 50">
                    <path class="path" d="
                    M 30 15
                    L 28 17
                    M 25.61 25.61
                    A 15 15, 0, 0, 1, 15 30
                    A 15 15, 0, 1, 1, 27.99 7.5
                    L 15 15
                    " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)" />
                  </svg>
                </div>
              </template>
              {{ scope.row.surveyAuditStatus }}
            </el-button>
            <a-tag v-else-if="scope.row.surveyAuditStatus === '失败'" color="error" style="
                text-align: center;
                line-height: 35px;
                height: 35px;
                width: 106px;
                margin-left: 10px;
              ">
              <template #icon>
                <close-circle-outlined />
              </template>
              失败
            </a-tag>
            <a-tag v-else-if="scope.row.surveyAuditStatus === '成功'" color="success" style="
                text-align: center;
                line-height: 35px;
                height: 35px;
                width: 106px;
                margin-left: 10px;
              ">
              <template #icon>
                <check-circle-outlined />
              </template>
              成功
            </a-tag>
            <a-tag v-else-if="scope.row.surveyAuditStatus === '安全终止'" color="error" style="
                text-align: center;
                line-height: 35px;
                height: 35px;
                width: 106px;
                margin-left: 10px;
              ">
              <template #icon>
                <check-circle-outlined />
              </template>
              安全终止
            </a-tag>
            <a-tag v-else-if="scope.row.surveyAuditStatus === '配额满'" color="warning" style="
                text-align: center;
                line-height: 35px;
                height: 35px;
                width: 106px;
                margin-left: 10px;
              ">
              <template #icon>
                <check-circle-outlined />
              </template>
              配额满
            </a-tag>
            <a-tag v-else-if="scope.row.surveyAuditStatus === '审核失败'" color="error" style="
                text-align: center;
                line-height: 35px;
                height: 35px;
                width: 106px;
                margin-left: 10px;
              ">
              <template #icon>
                <close-circle-outlined />
              </template>
              审核失败
            </a-tag>
            <a-tag v-else-if="scope.row.surveyAuditStatus === '超时失败'" color="error" style="
                text-align: center;
                line-height: 35px;
                height: 35px;
                width: 106px;
                margin-left: 10px;
              ">
              <template #icon>
                <close-circle-outlined />
              </template>
              超时失败
            </a-tag>
            <a-tag v-else-if="scope.row.surveyAuditStatus === '时间未达标审核失败'" color="error" style="
                text-align: center;
                line-height: 35px;
                height: 35px;
                width: 106px;
                margin-left: 10px;
              ">
              <template #icon>
                <close-circle-outlined />
              </template>
              时间未达标审核失败
            </a-tag>
            <a-tag style="
                text-align: center;
                line-height: 35px;
                height: 35px;
                width: 106px;
                margin-left: 10px;
              " :color="scope.row.surveyAuditStatus === '审核失败' ? 'error' : 'success'" v-else>
              {{ scope.row.surveyAuditStatus }}
            </a-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="调查ip" align="center" prop="surveyIp" />
      <el-table-column label="操作">
        <template #default="scope">
          <div>
            <el-button type="primary" icon="Edit" @click="openDialog(scope.row)">备注</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <editDialog ref="editDialogRef"></editDialog>
  </div>
</template>

<style scoped>
.el-button .custom-loading .circular {
  margin-right: 6px;
  width: 18px;
  height: 18px;
  animation: loading-rotate 2s linear infinite;
}

.el-button .custom-loading .circular .path {
  animation: loading-dash 1.5s ease-in-out infinite;
  stroke-dasharray: 90, 150;
  stroke-dashoffset: 0;
  stroke-width: 2;
  stroke: var(--el-button-text-color);
  stroke-linecap: round;
}
</style>

<script setup name="SurveyLog">
import { checkRole } from "@/utils/permission"; // 权限判断函数
// 获取用户权限
import useUserStore from "@/store/modules/user";
const userid = useUserStore().id;
const usernames = useUserStore().name;
import {
  CheckCircleOutlined,
  SyncOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined,
  MinusCircleOutlined,
} from "@ant-design/icons-vue";
import {
  listSurveyLog,
  getSurveyLog,
  delSurveyLog,
  addSurveyLog,
  updateSurveyLog,
  listSurveyLogByid,
  exportSurveyLog,
  batchExamine
} from "@/api/survey/surveyLog";
import editDialog from "./componenet/editDialog.vue"; //引入组件
import { message } from "ant-design-vue";
const editDialogRef = ref();
const { proxy } = getCurrentInstance();

const surveyLogList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const surveyUserIdStr = ref('')
const surveyAuditStatus = ref('')
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    surveyUserId: null,
    surveyUserLoginId: null,
    surveyId: null,
    surveyUserTitle: null,
    surveyUserPrice: null,
    surveyUserLanguage: null,
    surveyStartTime: null,
    surveyStopTime: null,
    surveyStatus: null,
    surveyAuditStatus: null,
    surveyIp: null,
    surveyFixedtime: null,
    surveyUserName: null,
    surveyUserLoginIdstring: null,
  },
  rules: {},
});

const options = [
  {
    value: "进行中",
    label: "进行中",
  },
  {
    value: "成功",
    label: "成功",
  },
  {
    value: "失败",
    label: "失败",
  },
  {
    value: "审核失败",
    label: "审核失败",
  },
  {
    value: "审核成功",
    label: "审核成功",
  },
  {
    value: "安全终止",
    label: "安全终止",
  },
  {
    value: "配额满",
    label: "配额满",
  },
  {
    value: "超时失败",
    label: "超时失败",
  },
  {
    value: "时间未达标审核失败",
    label: "时间未达标审核失败",
  },
];


const surveyAuditStatusOptions = [
  // {
  //   value: "进行中",
  //   label: "进行中",
  // },
  {
    value: "成功",
    label: "成功",
  },
  {
    value: "失败",
    label: "失败",
  },
  {
    value: "审核失败",
    label: "审核失败",
  },
  {
    value: "审核成功",
    label: "审核成功",
  },
  {
    value: "安全终止",
    label: "安全终止",
  },
  {
    value: "配额满",
    label: "配额满",
  },
  {
    value: "超时失败",
    label: "超时失败",
  },
  {
    value: "时间未达标审核失败",
    label: "时间未达标审核失败",
  },
  
];

const value = ref("");

const { queryParams, form, rules } = toRefs(data);

/** 查询调查记录列表 */
function getList() {
  loading.value = true;
  const hasAdminRole = checkRole(["admin"]); // 调用 checkRole 函数并传递包含 "admin" 的数组作为参数
  if (hasAdminRole) {
    // 根据 hasAdminRole 的值执行相应操作
    listSurveyLog(queryParams.value).then((response) => {
      surveyLogList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  } else {
    // 用户没有管理员角色,可能需要执行其他操作
    listSurveyLogByid(userid, queryParams.value).then((response) => {
      surveyLogList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    surveyUserId: null,
    surveyUserLoginId: null,
    surveyId: null,
    surveyUserTitle: null,
    surveyUserPrice: null,
    surveyUserLanguage: null,
    surveyStartTime: null,
    surveyStopTime: null,
    surveyStatus: null,
    surveyAuditStatus: null,
    surveyIp: null,
    surveyFixedtime: null,
    surveyUserName: null,
    surveyUserLoginIdstring: null,
  };
  proxy.resetForm("surveyLogRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  surveyUserIdStr.value = ''
  surveyAuditStatus.value = ''
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 排序触发事件 */
const defaultSort = ref({ prop: "surveyStartTime", order: "descending" });
function handleSortChange(column, prop, order) {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
}

function calculateDuration(startTime, stopTime) {
  // 将时间字符串转换为 JavaScript Date 对象
  const startTimeObj = new Date(startTime);

  // 如果 stopTime 为 null，直接返回 -1
  if (stopTime === null) {
    return -1;
  }

  const stopTimeObj = new Date(stopTime);

  // 计算时间差（以毫秒为单位）
  const durationMs = stopTimeObj - startTimeObj;

  // 将毫秒转换为分钟
  const durationMinutes = durationMs / (1000 * 60);

  // 返回耗时（分钟）
  return durationMinutes;
}

getList();

/**
 * 打开备注弹出框
 */
const openDialog = (row) => {
  editDialogRef.value.openDialog(row.id);
};
const handleBatchExamine = async (surveyAuditStatus) => {
if(!surveyAuditStatus.length) {
  return message.error('请选择状态')
}
  if (surveyUserIdStr.value.length) {
    await batchExamine({
      surveyUserIdStr: surveyUserIdStr.value,
      surveyAuditStatus,
      examineType: 1
    })
  }
  if (ids.value.length) {
    await batchExamine(
      {
        ids: ids.value,
        surveyAuditStatus,
        examineType: 0
      }
    )
  }
  getList();
}

const exportData = async () => {
  let obj = {};
  for (let key in queryParams.value) {
    if (
      queryParams.value.hasOwnProperty(key) &&
      queryParams.value[key] &&
      key !== "pageNum" &&
      key !== "pageSize"
    ) {
      obj[key] = queryParams.value[key];
    }
  }
  let res = await exportSurveyLog(obj);
  // 创建一个临时的URL对象
  const url = window.URL.createObjectURL(
    new Blob([res], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    })
  );
  // 创建一个<a>标签并设置其href属性
  const a = document.createElement("a");
  a.href = url;
  // 设置下载文件的默认名称
  a.download = "export.xlsx";
  // 将<a>标签添加到文档中
  document.body.appendChild(a);
  // 模拟点击<a>标签来触发下载
  a.click();
  // 下载完成后移除<a>标签和URL对象
  window.URL.revokeObjectURL(url);
  document.body.removeChild(a);
};
</script>
